package com.gao.controller.rabbit;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * Pub/Sub  发布/订阅模式
 * @author gaofeng
 * @date 2022年09月06日 19:44
 */
public class PubSubModelController {
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = MyChannelFactory.getConnection();
        // 4.创建channel
        Channel channel = connection.createChannel();
        /*
         * 5.创建交换机
            (String var1, BuiltinExchangeType var2, boolean var3, boolean var4, boolean var5, Map<String, Object> var6)
                var1:交换机名称
                var2:交换机的类型 ,"direct":定向......
                var3:是否持久化
                var4:是否自动删除
                var5:内部使用的,
                var6:参数
        */
        String exchangeName = "test_fanout" ;
        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.FANOUT, true, false, false, null) ;
        // 6.创建队列
        String queueName1 = "test_fanout_queue1" ;
        String queueName2 = "test_fanout_queue2" ;
        channel.queueDeclare(queueName1, true, false, false, null) ;
        channel.queueDeclare(queueName2, true, false, false, null) ;
        /*
         * 7. 绑定队列和交换机
         * String var1, String var2, String var3
         *  var1:队列名称
         * var2:交换机名称
         * var3:路由键,绑定规则
         */
        channel.queueBind(queueName1, exchangeName, "") ;
        channel.queueBind(queueName2, exchangeName, "") ;
        // 8.发送消息
        channel.basicPublish(exchangeName, "", null, "i love China!".getBytes(StandardCharsets.UTF_8));
        // 9.释放资源
        channel.close();
        connection.close();
    }
}
